//
//  AppDelegate.swift
//  SinaWeibo
//
//  Created by Arvin on 15/11/8.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SDWebImage

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
//        let navi = UINavigationController(rootViewController: ComposeViewController())
        window?.rootViewController = getRootController()
        window?.makeKeyAndVisible()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchVC:", name: switchController, object: nil)
        setThemColor()
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func getRootController() -> (UIViewController) {
        if UserAccountViewModel().userLogin {
            return isVersionChange() ? NewFeatureViewController() : WelcomeUserViewController()
        }
        return MainTabBarViewController()
    }
    
    // 注意: 跳转之前, 不要打印这个函数返回值情况
    private func isVersionChange() -> (Bool) {
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(versionStr)
        let userDefluat = NSUserDefaults.standardUserDefaults()
        let lastVersion = userDefluat.doubleForKey("CFBundleShortVersionString")
        if version == lastVersion {
            return false
        }
        userDefluat.setDouble(version!, forKey: "CFBundleShortVersionString")
        userDefluat.synchronize() // 注意: 同步
        return true
    }
    
    @objc func switchVC(n: NSNotification) {
        if (n.object != nil) {
            window?.rootViewController = WelcomeUserViewController()
        } else {
            window?.rootViewController = MainTabBarViewController()
        }
    }
    
    private func setThemColor() {
        UINavigationBar.appearance().tintColor = themColor
        UITabBar.appearance().tintColor = themColor
    }
    
    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        SDWebImageManager.sharedManager().cancelAll()
        SDImageCache.sharedImageCache().clearMemory()
    }
}

